<template>
  <div class="points-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>积分管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">刷新</el-button>
        <el-button type="success" @click="showAdjustDialog">调整积分</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" :key="renderKey">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.totalUsers }}</div>
              <div class="stats-label">总用户数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.totalPoints }}</div>
              <div class="stats-label">总积分</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-number">{{ computedStats.avgPoints }}</div>
              <div class="stats-label">平均积分</div>
            </div>
          </el-card>
        </el-col>

      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="积分范围">
          <el-input-number v-model="searchForm.minPoints" placeholder="最小积分" :min="0" style="width: 120px;"></el-input-number>
          <span style="margin: 0 8px;">-</span>
          <el-input-number v-model="searchForm.maxPoints" placeholder="最大积分" :min="0" style="width: 120px;"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="正常" value="normal"></el-option>
            <el-option label="积分不足" value="low"></el-option>
            <el-option label="积分充足" value="high"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">用户积分列表</div>
        <div class="table-actions">
          <el-button type="warning" @click="handleBatchExport" :disabled="!selectedRows.length">
            批量导出
          </el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="用户信息" width="200">
          <template slot-scope="scope">
            <div class="user-info">
              <el-avatar 
                :src="scope.row.avatar" 
                size="small"
                :icon="!scope.row.avatar ? 'el-icon-user' : ''"
              ></el-avatar>
              <div class="user-details">
                <div class="username">{{ scope.row.username }}</div>
                <div class="nickname">{{ scope.row.nickname }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="当前积分" width="120">
          <template slot-scope="scope">
            <span class="points-number">{{ scope.row.points }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalEarned" label="累计获得" width="120">
          <template slot-scope="scope">
            <span class="points-earned">{{ scope.row.totalEarned }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalUsed" label="累计使用" width="120">
          <template slot-scope="scope">
            <span class="points-used">{{ scope.row.totalUsed }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="lastUpdateTime" label="最后更新" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.lastUpdateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="viewUserPoints(scope.row)">
              查看详情
            </el-button>
            <el-button type="warning" size="mini" @click="adjustUserPoints(scope.row)">
              调整积分
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 积分调整对话框 -->
    <el-dialog title="调整用户积分" :visible.sync="adjustDialogVisible" width="500px">
      <el-form :model="adjustForm" :rules="adjustRules" ref="adjustForm" label-width="100px">
        <el-form-item label="用户信息">
          <div class="user-info-display">
            <span>{{ adjustForm.username }}</span>
            <span class="current-points">当前积分: {{ adjustForm.currentPoints }}</span>
          </div>
        </el-form-item>
        <el-form-item label="调整类型" prop="adjustType">
          <el-radio-group v-model="adjustForm.adjustType">
            <el-radio label="add">增加积分</el-radio>
            <el-radio label="subtract">减少积分</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分数量" prop="points">
          <el-input-number 
            v-model="adjustForm.points" 
            :min="1" 
            :max="adjustForm.adjustType === 'subtract' ? adjustForm.currentPoints : 999999"
            style="width: 100%">
          </el-input-number>
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-input v-model="adjustForm.reason" placeholder="请输入调整原因"></el-input>
        </el-form-item>
        <el-form-item label="详细说明" prop="description">
          <el-input 
            type="textarea" 
            v-model="adjustForm.description" 
            placeholder="请输入详细说明"
            :rows="3">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adjustDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdjust" :loading="adjustLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 积分详情对话框 -->
    <el-dialog title="用户积分详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="selectedUser" class="user-points-detail">
        <div class="user-basic-info">
          <el-avatar :src="selectedUser.avatar" size="large"></el-avatar>
          <div class="user-info">
            <h3>{{ selectedUser.username }}</h3>
            <p>{{ selectedUser.nickname }}</p>
          </div>
          <div class="points-summary">
            <div class="points-item">
              <span class="label">当前积分:</span>
              <span class="value">{{ selectedUser.points }}</span>
            </div>
            <div class="points-item">
              <span class="label">累计获得:</span>
              <span class="value">{{ selectedUser.totalEarned }}</span>
            </div>
            <div class="points-item">
              <span class="label">累计使用:</span>
              <span class="value">{{ selectedUser.totalUsed }}</span>
            </div>
          </div>
        </div>
        
        <el-tabs v-model="activeTab" class="points-tabs">
          <el-tab-pane label="积分记录" name="records">
            <el-table :data="pointsRecords" style="width: 100%">
              <el-table-column prop="type" label="类型" width="100">
                <template slot-scope="scope">
                  <el-tag :type="getTypeTagType(scope.row.type)">
                    {{ getTypeLabel(scope.row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="points" label="积分" width="100">
                <template slot-scope="scope">
                  <span :class="getPointsClass(scope.row.type)">
                    {{ scope.row.type === 'used' ? '-' : '+' }}{{ scope.row.points }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="标题"></el-table-column>
              <el-table-column prop="source" label="来源" width="120"></el-table-column>
              <el-table-column prop="createTime" label="时间" width="160">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          

        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import pointsApi from '@/api/points-management'

export default {
  name: 'PointsManagement',
  data() {
    return {
      renderKey: 0,
      loading: false,
      adjustLoading: false,
      searchForm: {
        username: '',
        minPoints: null,
        maxPoints: null,
        status: ''
      },
      tableData: [],
      selectedRows: [],
      pagination: {
        current: 1,
        size: 20,
        total: 0
      },
      adjustDialogVisible: false,
      detailDialogVisible: false,
      adjustForm: {
        userId: null,
        username: '',
        currentPoints: 0,
        adjustType: 'add',
        points: 1,
        reason: '',
        description: ''
      },
      adjustRules: {
        adjustType: [
          { required: true, message: '请选择调整类型', trigger: 'change' }
        ],
        points: [
          { required: true, message: '请输入积分数量', trigger: 'blur' }
        ],
        reason: [
          { required: true, message: '请输入调整原因', trigger: 'blur' }
        ]
      },
      selectedUser: null,
      pointsRecords: [],

      activeTab: 'records'
    }
  },
  computed: {
    computedStats() {
      if (this.tableData.length === 0) {
        return {
          totalUsers: 0,
          totalPoints: 0,
          avgPoints: 0
        }
      }
      
      const totalPoints = this.tableData.reduce((sum, user) => sum + user.points, 0)
      const avgPoints = Math.round(totalPoints / this.tableData.length)
      
      return {
        totalUsers: this.tableData.length,
        totalPoints: totalPoints,
        avgPoints: avgPoints
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.current,
          count: this.pagination.size,
          ...this.searchForm
        }
        console.log('发送请求参数:', params)
        
        const response = await pointsApi.getUserPointsList(this.$axios, params)
        
        // 添加调试日志
        console.log('API响应数据:', response)
        console.log('response.data:', response.data)
        console.log('response.records:', response.records)
        
        // 检查数据结构：可能是response.data.records或直接response.records
        const records = response.data && response.data.records ? response.data.records : 
                       response.records ? response.records : null
        
        if (records && records.length > 0) {
          console.log('使用真实数据，记录数:', records.length)
          // 处理后端返回的数据，确保字段兼容
          this.tableData = records.map(record => {
            console.log('处理记录:', record)
            return {
              id: record.id || record.user_id,
              username: record.username || record.nickname || `用户${record.id || record.user_id}`,
              nickname: record.nickname || `用户${record.id || record.user_id}`,
              avatar: record.avatar || '',
              points: record.points || record.current_points || 0,
              totalEarned: record.totalEarnedPoints || record.total_earned || record.totalEarned || 0,
              totalUsed: record.totalUsedPoints || record.total_used || record.totalUsed || 0,
              lastUpdateTime: new Date()
            }
          })
          // 获取总数：可能是response.data.total或直接response.total
          const total = response.data && response.data.total ? response.data.total : 
                       response.total ? response.total : records.length
          this.pagination.total = total
        } else {
          console.log('没有数据，原因:', {
            hasData: !!response.data,
            hasRecords: !!(response.data && response.data.records),
            recordsLength: response.data && response.data.records ? response.data.records.length : 0,
            directRecords: !!response.records,
            recordsLengthDirect: response.records ? response.records.length : 0
          })
          // 没有数据时显示空列表
          this.tableData = []
          this.pagination.total = 0
        }
      } catch (error) {
        this.$message.error('获取数据失败')
        console.error(error)
        
        // API调用失败时显示空列表
        this.tableData = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      this.pagination.current = 1
      this.fetchData()
    },
    
    handleReset() {
      this.searchForm = {
        username: '',
        minPoints: null,
        maxPoints: null,
        status: ''
      }
      this.handleSearch()
    },
    
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchData()
    },
    
    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchData()
    },
    
    refreshData() {
      this.renderKey++
      this.fetchData()
    },
    
    showAdjustDialog() {
      this.adjustForm = {
        userId: null,
        username: '',
        currentPoints: 0,
        adjustType: 'add',
        points: 1,
        reason: '',
        description: ''
      }
      this.adjustDialogVisible = true
    },
    
    adjustUserPoints(user) {
      this.adjustForm = {
        userId: user.id,
        username: user.username,
        currentPoints: user.points,
        adjustType: 'add',
        points: 1,
        reason: '',
        description: ''
      }
      this.adjustDialogVisible = true
    },
    
    async submitAdjust() {
      try {
        await this.$refs.adjustForm.validate()
        
        this.adjustLoading = true
        
        // 转换为后端期望的下划线格式
        const requestData = {
          user_id: this.adjustForm.userId,
          adjust_type: this.adjustForm.adjustType,
          points: this.adjustForm.points,
          reason: this.adjustForm.reason,
          description: this.adjustForm.description
        }
        
        const response = await pointsApi.adjustUserPoints(this.$axios, requestData)
        
        // 检查响应数据：可能是response.data或直接response
        const responseData = response.data || response
        
        if (responseData && responseData.id) {
          this.$message.success('积分调整成功')
          this.adjustDialogVisible = false
          
          // 重置搜索条件，获取所有用户数据
          this.searchForm = {
            username: '',
            minPoints: null,
            maxPoints: null,
            status: ''
          }
          this.pagination.current = 1
          this.fetchData()
        } else {
          this.$message.error('积分调整失败')
        }
        
      } catch (error) {
        if (error !== false) {
          this.$message.error('积分调整失败')
          console.error(error)
        }
      } finally {
        this.adjustLoading = false
      }
    },
    
    async viewUserPoints(user) {
      this.selectedUser = user
      this.detailDialogVisible = true
      
      try {
        // 获取用户积分记录
        const recordsResponse = await pointsApi.getUserPointsRecords(this.$axios, user.id, {
          page: 1,
          count: 100
        })
        
        console.log('积分记录API响应:', recordsResponse)
        
        // 检查数据结构：可能是recordsResponse.data.records或直接recordsResponse.records
        const records = recordsResponse.data && recordsResponse.data.records ? recordsResponse.data.records : 
                       recordsResponse.records ? recordsResponse.records : null
        
        if (records && records.length > 0) {
          console.log('使用真实积分记录数据，记录数:', records.length)
          this.pointsRecords = records
        } else {
          console.log('没有积分记录数据，原因:', {
            hasData: !!recordsResponse.data,
            hasRecords: !!(recordsResponse.data && recordsResponse.data.records),
            recordsLength: recordsResponse.data && recordsResponse.data.records ? recordsResponse.data.records.length : 0,
            directRecords: !!recordsResponse.records,
            recordsLengthDirect: recordsResponse.records ? recordsResponse.records.length : 0
          })
          // 没有积分记录时显示空列表
          this.pointsRecords = []
        }
        

        
      } catch (error) {
        this.$message.error('获取用户积分详情失败')
        console.error(error)
        
        // API调用失败时显示空列表
        this.pointsRecords = []
      }
    },
    
    handleBatchExport() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要导出的数据')
        return
      }
      
      // 实现批量导出功能
      this.$message.success(`已选择 ${this.selectedRows.length} 条数据进行导出`)
    },
    
    formatDate(date) {
      if (!date) return '-'
      return new Date(date).toLocaleString()
    },
    
    getTypeTagType(type) {
      const typeMap = {
        earned: 'success',
        used: 'danger',

        adjusted: 'info'
      }
      return typeMap[type] || 'info'
    },
    
    getTypeLabel(type) {
      const labelMap = {
        earned: '获得',
        used: '使用',
        adjusted: '调整'
      }
      return labelMap[type] || type
    },
    
    getPointsClass(type) {
      return type === 'used' ? 'points-negative' : 'points-positive'
    }
  }
}
</script>

<style scoped lang="scss">
.points-management {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .stats-cards {
    margin-bottom: 20px;
    
    .stats-card {
      .stats-content {
        text-align: center;
        padding: 20px;
        
        .stats-number {
          font-size: 24px;
          font-weight: bold;
          color: #409EFF;
          margin-bottom: 8px;
        }
        
        .stats-label {
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
  
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
  
  .table-card {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .table-title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
      
      .table-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .user-details {
      .username {
        font-weight: bold;
        color: #303133;
      }
      
      .nickname {
        font-size: 12px;
        color: #909399;
      }
    }
  }
  
  .points-number {
    font-weight: bold;
    color: #409EFF;
  }
  
  .points-earned {
    color: #67C23A;
  }
  
  .points-used {
    color: #F56C6C;
  }
  

  
  .user-info-display {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .current-points {
      color: #409EFF;
      font-weight: bold;
    }
  }
  
  .user-points-detail {
    .user-basic-info {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid #EBEEF5;
      
      .user-info {
        h3 {
          margin: 0 0 5px 0;
          color: #303133;
        }
        
        p {
          margin: 0;
          color: #909399;
        }
      }
      
      .points-summary {
        margin-left: auto;
        
        .points-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 5px;
          
          .label {
            color: #606266;
            margin-right: 10px;
          }
          
          .value {
            font-weight: bold;
            color: #409EFF;
          }
        }
      }
    }
    
    .points-tabs {
      .no-data {
        text-align: center;
        color: #909399;
        padding: 40px 0;
      }
    }
  }
  
  .points-positive {
    color: #67C23A;
    font-weight: bold;
  }
  
  .points-negative {
    color: #F56C6C;
    font-weight: bold;
  }
}
</style>
